package indexer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import org.annolab.tt4j.TokenHandler;
import org.annolab.tt4j.TreeTaggerException;
import org.annolab.tt4j.TreeTaggerWrapper;

public class Term {
	private final String mot;
	private final String radical;
	private Integer idBd;
	private final ArrayList<Document> listeDocuments;

	public Term(String mot) throws IOException, TreeTaggerException {
		this.mot = mot.trim();
		this.idBd = null;
		this.listeDocuments = new ArrayList<>();

		// Calcul du radical
		this.radical = this.lemme(this.mot);
	}

	public int getNbDocuments() {
		return this.listeDocuments.size();
	}

	public String getRadical() {
		return this.radical;
	}

	public Integer getIdBd() {
		return this.idBd;
	}

	public void setIdBd(int idBd) {
		if (idBd > 0) {
			this.idBd = idBd;
		} else {
			throw new IllegalArgumentException("Le paramètre doit être un entier strictement positif.");
		}
	}

	public void addDocument(Document doc) {
		if (!this.listeDocuments.contains(doc)) {
			this.listeDocuments.add(doc);
		}
	}

	/**
	 *
	 * @param obj
	 * @return
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}

		if (obj == null) {
			return false;
		}

		if (this.getClass() != obj.getClass()) {
			return false;
		}

		Term other = (Term) obj;

		return this.getRadical().equals(other.getRadical());
	}

	@Override
	public int hashCode() {
		int hash = 7;
		hash = (13 * hash) + Objects.hashCode(this.radical);
		return hash;
	}

	@Override
	public String toString() {
		return this.getRadical();
	}

	public String lemme(String mot) throws IOException, TreeTaggerException {
		// Point TT4J to the TreeTagger installation directory. The executable is expected
		// in the "bin" subdirectory - in this example at "/opt/treetagger/bin/tree-tagger"
		System.setProperty("treetagger.home", "C:\\TreeTagger");
		TreeTaggerWrapper tt = new TreeTaggerWrapper<String>();
		final List<String> lemme = new ArrayList<String>();
		try {
			tt.setModel("C:\\TreeTagger\\lib\\french-utf8.par");
			tt.setHandler(new TokenHandler<String>() {
				@Override
				public void token(String token, String pos, String lemma) {
					lemme.add(lemma);
				}
			});
			tt.process(Arrays.asList(new String[] { mot }));
		}
		finally {
			tt.destroy();
		}
		return lemme.get(0);

	}
}
